package com.zhanghe.study.io.old;

import java.io.*;

/**
 * 对象流
 * ObjectInputStream
 * ObjectOutputStream
 * 对象的序列化
 * 不能序列化 static和transient修饰的成员变量
 */
public class TestObjectStream {

    public static void main(String[] args) {
//        testObjectOutputStream();
        testObjectInputStream();
    }

    // 对象序列化   把对象转为二进制 放到文件中
    private static void testObjectOutputStream(){
        Person person = new Person();
        person.age = 10;
        person.name = "张三";
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("object.txt"));
            oos.writeObject(person);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos != null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    // 对象反序列化  将文件通过ObjectInputStream转换为对象
    private static void testObjectInputStream(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.txt"));
            Person person = (Person) ois.readObject();
            System.out.println(person.age);
            System.out.println(person.name);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Person implements Serializable {
        private static final long serialVersionUID = 1L;
        String name;
        int age;
        double weight;


    }
}
